package com.mlh.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mlh.entity.Article;
import com.mlh.entity.Category;
import com.mlh.mapper.CategoryMapper;
import com.mlh.service.ArticleService;
import com.mlh.service.CategoryService;
import com.mlh.util.BeanCopyUtil;
import com.mlh.util.ResponseResult;
import com.mlh.vo.CategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分类表(Category)表服务实现类
 *
 * @author makejava
 * @since 2024-03-12 22:04:42
 */
@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private ArticleService articleService;

    //获得有正式文章的分类列表
    @Override
    public ResponseResult getCategoryList() {
        //查询文章表 状态为已发布的文章
        LambdaQueryWrapper<Article> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus,0);
        List<Article> articleList = articleService.list(queryWrapper);
        //获取文章的分类id，并且去重
        //            对应的匿名内部类代码
        //         .map(new Function<Article, Long>() {
        //             @Override
        //             public Long apply(Article article) {
        //                 return article.getCategoryId();
        //             }
        //         })
        Set<Long> categoryIds = articleList.stream()
                .map(article -> article.getCategoryId())
                .collect(Collectors.toSet());

        //通过得到的种类列表 查询出对应的种类返回
        List<Category> categories = listByIds(categoryIds);
        //过滤 只保留状态正常的种类
        categories = categories.stream()
                .filter(category -> "0".equals(category.getStatus()))
                .collect(Collectors.toList());
        //封装vo
        List<CategoryVo> categoryVos = BeanCopyUtil.copyBeanList(categories, CategoryVo.class);
        return  ResponseResult.okResult(categoryVos);
    }
}
